package val.to.UI;

import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;

import val.to.BitmapUtil;
import val.to.ErrorHelper;
import val.to.Globals;
import val.to.R;
import val.to.entities.UploadItem;
import val.to.entities.UploadItem.UploadStatus;
import val.to.uploader.ItemStatusChangedListener;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class PhotoUploadQueue extends Activity {

	ListView mList;
	QueueAdapter mAdapter;
	Button mClearAllButton;
	Button mClearCompletedButton;
	public static boolean IsVisible;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.photo_upload_queue);
		mList = (ListView) findViewById(R.id.photo_upload_list);
		mClearAllButton = (Button) findViewById(R.id.clearAllUploadsButton);
		mClearCompletedButton = (Button) findViewById(R.id.clearCompletedUploadsButton);

		mClearAllButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Globals.UploadManager.removeAllUploads();
				mAdapter.notifyDataSetChanged();
			}
		});

		mClearCompletedButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Globals.UploadManager.removeCompletedUploads();
				mAdapter.notifyDataSetChanged();
			}
		});

		mAdapter = new QueueAdapter(this);
		mList.setAdapter(mAdapter);
	}

	@Override
	public void onResume() {
		super.onResume();
		IsVisible = true;
		mAdapter.Register();
	}

	@Override
	public void onPause() {
		super.onPause();
		IsVisible = false;
		mAdapter.UnRegister();
	}

	private class QueueAdapter extends ArrayAdapter<UploadItem> {
		private LayoutInflater inflater = null;

		public QueueAdapter(Context context) {
			super(context, R.layout.photo_upload_queue_row);
			inflater = (LayoutInflater) PhotoUploadQueue.this
					.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		class ViewHolder {
			public ImageView thumbnail;
			public TextView title;
			public TextView secondaryTitle;
			public TextView time;
			public LinearLayout container;
			public TextView errorDeatils;
		}

		public void UnRegister() {
			Globals.UploadManager.setOnStatusChangedListener(null);
		}

		public void Register() {
			Globals.UploadManager
					.setOnStatusChangedListener(new ItemStatusChangedListener() {
						@Override
						public void onItemChanged() {
							PhotoUploadQueue.this.runOnUiThread(new Runnable() {
								@Override
								public void run() {
									QueueAdapter.this.notifyDataSetChanged();
								}
							});
						}
					});

			notifyDataSetChanged();
		}

		@Override
		public int getCount() {
			return Globals.UploadManager.getCount();
		}

		@Override
		public UploadItem getItem(int position) {
			return Globals.UploadManager.getItem(position);
		}

		@Override
		public long getItemId(int position) {
			return ((UploadItem) Globals.UploadManager.getItem(position))
					.getID();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View vi = convertView;
			ViewHolder holder = null;
			try {
				if (convertView == null) {
					vi = inflater
							.inflate(R.layout.photo_upload_queue_row, null);
					holder = new ViewHolder();
					holder.title = (TextView) vi.findViewById(R.id.title);
					holder.secondaryTitle = (TextView) vi
							.findViewById(R.id.secondLine);
					holder.time = (TextView) vi.findViewById(R.id.time);
					holder.thumbnail = (ImageView) vi
							.findViewById(R.id.list_image);
					holder.errorDeatils = (TextView) vi
							.findViewById(R.id.errorDetailsLink);

					holder.container = (LinearLayout) vi
							.findViewById(R.id.QueueButtonContainer);

					vi.setTag(holder);
				}

				if (holder == null)
					holder = (ViewHolder) vi.getTag();
				holder.container.removeAllViewsInLayout();
				final UploadItem item = (UploadItem) getItem(position);

				if (item.getStatus() == UploadStatus.Uploading) {
					ProgressBar bar = new ProgressBar(PhotoUploadQueue.this);
					holder.container.addView(bar);
				} else {
					ImageButton button = new ImageButton(PhotoUploadQueue.this);
					button.setScaleType(ScaleType.FIT_XY);
					holder.container.addView(button);
					if (item.getStatus() == UploadStatus.Uploaded)
						button.setBackgroundResource(R.drawable.queue_completed);
					else if (item.getStatus() == UploadStatus.Canceled)
						button.setBackgroundResource(R.drawable.queue_retry);
					else if (item.getStatus() == UploadStatus.Error) {
						button.setBackgroundResource(R.drawable.queue_retry);
						button.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								Globals.UploadManager.ReUploadItem(item);
							}
						});
					} else if (item.getStatus() == UploadStatus.Pending) {
						button.setBackgroundResource(R.drawable.queue_delete);
						button.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								Globals.UploadManager.DeleteItem(item);
								notifyDataSetChanged();
							}
						});
					}
				}

				// Setting all values in listview
				if (item.getStatus() == UploadStatus.Error) {
					holder.secondaryTitle.setVisibility(View.VISIBLE);
					holder.secondaryTitle.setText(item.getErrorMessage());
					if (item.getErrorDetails() != null) {
						holder.errorDeatils.setVisibility(View.VISIBLE);
						holder.errorDeatils
								.setOnClickListener(new OnClickListener() {
									@Override
									public void onClick(View v) {
										ErrorHelper.showErrorAlert(
												v.getContext(),
												getString(R.string.error_details_title),
												item.getErrorDetails());
									}
								});
					}
				} else {
					holder.secondaryTitle.setVisibility(View.INVISIBLE);
					holder.errorDeatils.setVisibility(View.INVISIBLE);
				}
				holder.title.setText(item.getStatus().toString());
				SimpleDateFormat df = new SimpleDateFormat("HH:mm");
				holder.time.setText(df.format(item.getStartTime().getTime()));

				if (item.getThumbnail() == null) {
					new AsyncImageLoader(holder).execute(item);
					holder.thumbnail.setImageBitmap(null);
				} else
					holder.thumbnail.setImageBitmap(item.getThumbnail());

				return vi;
			} catch (Exception e) {
				Log.d("error", e.getMessage());
			}
			return null;
		}

		private class AsyncImageLoader extends
				AsyncTask<UploadItem, Void, Bitmap> {
			ViewHolder mHolder;

			public AsyncImageLoader(ViewHolder Holder) {
				mHolder = Holder;
			}

			@Override
			protected Bitmap doInBackground(UploadItem... items) {
				try {
					items[0].setThumbnail(BitmapUtil.loadBitmap(
							items[0].getImageUri(), PhotoUploadQueue.this, 100,
							100, true, true));
				} catch (FileNotFoundException e) {
					mHolder.title.setText("Image not Found");
					items[0].SetStatus(UploadStatus.Error);
					return null;
				} catch (Exception e) {
					// mHolder.title.setText("Error: " + e.getMessage());
					items[0].SetStatus(UploadStatus.Error);
					return null;
				}

				return items[0].getThumbnail();
			}

			@Override
			protected void onPostExecute(Bitmap result) {
				if (result != null)
					mHolder.thumbnail.setImageBitmap(result);
			}

		}
	}
}
